<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="ruleForm.email" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="ruleForm.phone" />
    </el-form-item>
    <el-form-item label="中文昵称" prop="nickname">
      <el-input v-model.number="ruleForm.nickname" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        Submit
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
  import { reactive, ref } from "vue";
  import { isEmail, isPhone, isChina } from "/@/utils/validate";
  /**
   * @var
   */
  const ruleFormRef = ref();

  const validateChina = (rule, value, callback) => {
    if (!isChina(value)) {
      callback(new Error("请输入正确的昵称【2-4位】"));
    } else {
      callback();
    }
  };
  const validatePhone = (rule, value, callback) => {
    if (!isPhone(value)) {
      callback(new Error("请输入正确的手机号"));
    } else {
      callback();
    }
  };
  const validateEmail = (rule, value, callback) => {
    if (!isEmail(value)) {
      callback(new Error("请输入正确的邮箱"));
    } else {
      callback();
    }
  };

  const ruleForm = reactive({
    email: "",
    phone: "",
    nickname: "",
  });

  const rules = reactive({
    email: [{ validator: validateEmail, trigger: "blur" }],
    phone: [{ validator: validatePhone, trigger: "blur" }],
    nickname: [{ validator: validateChina, trigger: "blur" }],
  });

  /**
   * @method
   */
  const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate((valid) => {
      if (valid) {
        console.log("submit!");
      } else {
        console.log("error submit!");
        return false;
      }
    });
  };

  const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
  };
</script>
